package cn.wh.basic.interceptor;

import cn.wh.basic.anno.PreAuthorize;
import cn.wh.basic.jwt.JwtUtils;
import cn.wh.basic.jwt.LoginResult;
import cn.wh.basic.jwt.Payload;
import cn.wh.basic.jwt.RsaUtils;
import cn.wh.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

//    @Autowired
//    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token
        String token = request.getHeader("U-TOKEN");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        //如果获取到了
        if (StringUtils.hasLength(token)) {
            //从redis中获取token
            Object tokenTmp = redisTemplate.opsForValue().get(token);
            // 现在我们需要解密JWT串得到登录人和登录对应的权限
            //获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            //使用公钥进行解密jwt串
            Payload<LoginResult> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginResult.class);
            LoginResult loginResult = payload.getUserInfo();
            //刷新过期时间
            if (loginResult != null){
                //增加权限校验====即 登录之后，也需要查看是否有权限访问某个资源
                //1.区分是否是员工，是就需要校验权限
                Logininfo logininfo = loginResult.getLogininfo();
                if (logininfo.getType() == 0){
                    //。得到当前请求的资源 url
                    HandlerMethod method = (HandlerMethod) handler;
                    PreAuthorize authorize = method.getMethodAnnotation(PreAuthorize.class);
                    if (authorize != null){
                        //本次请求的sn
                        String currentSn  = authorize.value();
                        //。查询出当前登录人拥有的权限的资源 permissions
                        //List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
                        //。判断permissions是否包含url
                        if (!loginResult.getPermissions().contains(currentSn)){
                            //。 不包含。。提示权限不足，请联系管理员
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;//阻止放行
                        }
                    }
                }
                //redisTemplate.opsForValue().set(token,tokenTmp,30,TimeUnit.MINUTES );
                //登陆了 放行
                return true;
            }
        }
        //如果没拿到,则返回登录页面
        PrintWriter writer = response.getWriter();
        //以json格式返回noLogin   得到nologin后传给前端,让前端跳转到登录界面
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        //阻止放行
        return false;
    }
}